<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Address;
use App\Http\Controllers\Api\V1\Resources\AddressResource;
use App\Http\Controllers\Api\V1\Requests\AddressStoreRequest;
use App\Http\Controllers\Api\V1\Requests\AddressUpdateRequest;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use App\Services\MakeUserDeliveryAddress\MakeUserDeliveryAddress;
use App\Services\MakeUserDeliveryAddress\UpdateUserDeliveryAddress;
use App\Services\MakeUserDeliveryAddress\MakeUserDeliveryAddressRequest;
use App\Services\MakeUserDeliveryAddress\UpdateUserDeliveryAddressRequest;

class AddressesController extends Controller
{
	public function index(): AnonymousResourceCollection
	{
		$addresses = request()->user()->addresses()->paginate();;
		return AddressResource::collection($addresses);
	}

	public function store(MakeUserDeliveryAddressRequest $request): AddressResource
	{
		$address = app(MakeUserDeliveryAddress::class, [
			'request' => $request,
		])->make();

		return new AddressResource($address);
	}

	public function show(Address $address): AddressResource
	{
		return new AddressResource($address);
	}

	public function def()
	{
		$address = request()->user()->getDefaultAddress();
		return $address ? new AddressResource($address) : response(json_encode((object)$address));
	}

	public function update(UpdateUserDeliveryAddressRequest $request, Address $address)
	{
		$this->authorize('own', $address);

		app(UpdateUserDeliveryAddress::class, [
			'request' => $request,
			'address' => $address,
		])->update();

		return response(null, 204);
	}

	public function destroy(Address $address)
	{
		$this->authorize('own', $address);
		$address->delete();
		return response(null, 204);
	}
}
